package aInterview.xiaomi;


//TODO:2023/10/17  今天面试被面到的 三个线程交替打印 1到100
//TODO:2023/10/17 搞不清楚为什么我的这个代码就不会打印出结束标志呢
//TODO:2023/10/17  被面试官吐槽 ，实现过于复杂
public class JiaoTi1 {

    volatile  String  CODE="A";
    volatile   int  COUNT_NUM=1;

    public static void main(String[] args) {
        JiaoTi1 main1 = new JiaoTi1();
//TODO:2023/10/17  面试的时候lamda表达式忘记写了

        new Thread(()->{
                for (int i = 0; i < 34; i++) {
                    main1.printA();
                }

        },"线程A").start();


        new Thread(()->{
            for (int i = 0; i < 33; i++) {
                main1.printB();
            }
        },"线程B").start();


        new Thread(()->{
            for (int i = 0; i < 33; i++) {
                main1.printC();
            }
        },"线程C").start();

    }

    public  void printA(){
        synchronized (this){
            while (!CODE.equals("A")){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(COUNT_NUM++);
            CODE="B";
            //TODO:2023/10/17  这里必须是notifyAll()
            notifyAll();
        }
    }


    public  void printB(){
        synchronized (this){
            while (!CODE.equals("B")){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(COUNT_NUM++);
            CODE="C";
            notifyAll();
        }
    }


    public  void printC(){
        synchronized (this){
            while (!CODE.equals("C")){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(COUNT_NUM++);
            CODE="A";
            notifyAll();
        }
    }


}
